﻿using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Text;

public class XMLValidator
{
    private static bool isValid = true;

    // Validation Error Count
    static int ErrorsCount = 0;

    // Validation Error Message
    static string ErrorMessage = "";

    public static void ValidationHandler(object sender, ValidationEventArgs args)
    {
        isValid = false;
        ErrorMessage += ErrorMessage + args.Message + "\r\n";
        ErrorsCount++;
    }

    public static void Validate(string pathToXMLFile, string pathToSchemaFile)
    {       
        var readerSetting = new XmlReaderSettings();
        readerSetting.Schemas.Add(null, pathToSchemaFile);
        readerSetting.ValidationType = ValidationType.Schema;
        readerSetting.ValidationEventHandler += new ValidationEventHandler(ValidationHandler);        
        XmlReader xmlReader = XmlReader.Create(pathToXMLFile, readerSetting);
        while (xmlReader.Read()) ;
        
        if (ErrorsCount > 0)
        {
            throw new Exception(ErrorMessage);
        }

        

    }

    public static bool ValidateStringXML(string xml, string pathToSchemaFile, ref string errorMessage)
    {        
        var readerSetting = new XmlReaderSettings();
        readerSetting.Schemas.Add(null, pathToSchemaFile);
        readerSetting.ValidationType = ValidationType.Schema;
        readerSetting.ValidationEventHandler += new ValidationEventHandler(ValidationHandler);        
        XmlReader xmlReader = XmlReader.Create(new StringReader(xml), readerSetting);
        
        while (xmlReader.Read()) ;

        if (ErrorsCount > 0)
        {
            errorMessage = ErrorMessage;
            return false;
        }
        else
            return true;
    } 
}
